import suds
import base64
import pymysql
import json
from flask import request, Flask, jsonify
import pandas as pd
app = Flask(__name__)

mysqlDB = pymysql.connect(host='rm-uf6o0tz5x518u8os5so.mysql.rds.aliyuncs.com',port=13306,user='hs_ipc_prod_db',password='JR5hBZaIP1O%ittxw@cU',database='hs_ipc_prod_db')
cursor = mysqlDB.cursor()

deviceGetAllDataView = pd.read_csv('./DataConfig/deviceGetAllDataView.csv',encoding="ANSI")
deviceSetAllDataView = pd.read_csv('./DataConfig/deviceSetAllDataView.csv',encoding='ANSI')


url = 'http://127.0.0.1:5080/?wsdl'
client = suds.client.Client(url)
print(client) 

## 上位机按下按键
@app.route('/insert/MMM')
def getbyDate():

    MMMResult =  client.service.GetVarValue("123",7,"MMM")


    sql = "INSERT INTO `hs_ipc_prod_db`.`beta_biz_device_state_log` ( `id`, `device_type_code`, `device_code`, `device_name`, `production_line_code`, `device_state`, `sync_time`, `operate_time`, `accumulate_consecutive_capacity`, `create_time` )VALUES( NULL, '1', '1', '"+str(MMMResult)+"', '1', 'NORMAL', '2023-03-10 10:08:58', '2023-03-10 10:09:20', 1, '2023-03-10 10:09:26' );"
    
    print(sql)

    try:
        cursor.execute(sql)
        mysqlDB.commit()

    except Exception as e:
        mysqlDB.rollback()
        print("查询失败")
        print(e)

    
    return {"msg": "error","data":""}


## mes系统读取多设备信息
@app.route('/getDeviceAllValue',methods=['GET'])
def getDeviceAllValue():

    deviceId = request.args['deviceId']

    readValueKey = ""
    for indexs in deviceGetAllDataView.index:
        viewData = deviceGetAllDataView.loc[indexs]
        readValueKey += ''.join(viewData.values[0:1]) +"."+ "DEVICE"+ str(deviceId) +"_"+ ''.join(viewData.values[1:2]) + "|"

    print("getDeviceAllValue:"+readValueKey)

    if len(readValueKey) == 0:
        return {"msg": "error,no data true"}

    result = client.service.ReadVarValues("123",readValueKey).split('|')

    outResult = {}
    resultIndex = 1

    for indexs in deviceGetAllDataView.index:
        jsonKey = deviceGetAllDataView.loc[indexs].values[1:2]
        outResult[''.join(jsonKey)] = result[resultIndex]
        resultIndex = resultIndex + 1
    
    outResult["deviceId"] = deviceId
    
    return {"msg": "success","data":outResult}


@app.route('/setDeviceAllValue',methods=['POST'])
def setDeviceAllValue():

    setData = request.json
    deviceId = setData["deviceId"]

    writeKeyStr = ""
    writeValueStr = ""
    setStatusValue = []

    for indexs in deviceSetAllDataView.index:
        viewData = deviceSetAllDataView.loc[indexs]
        viewTopic = ''.join(viewData.values[1:2])

        if setData.get(viewTopic) != None:
            setStatusValue.append(viewTopic)
            writeKeyStr += ''.join(viewData.values[0:1]) +"."+ "DEVICE"+ str(deviceId) +"_"+ ''.join(viewData.values[1:2]) + "|"
            writeValueStr += str(setData.get(viewTopic))+"|"

    
    print("setDeviceValueresult:"+writeKeyStr+","+writeValueStr)

    if len(writeKeyStr) == 0 | len(writeValueStr) == 0:
        return {"msg": "error,no data true"}

    result = client.service.WriteVarValues("1234",writeKeyStr,writeValueStr)
    resultArray = result.split(":")[-1].split('|')
    outResult = {}

    outResultIndex = 0
    for value in setStatusValue:
        outResult[value] = resultArray[outResultIndex]

    print(outResult)
    
    return {"msg": "success","data": outResult}

    
try:
    app.run(port=8066)
except BaseException:
    print("服务启动失败,端口:8066")